import { Models } from '../../../../common/typings/model'
import KoaRouter from 'koa-router'
import Mysql from '../../../../core/Mysql'
import httpErrors from '../../../../core/HttpException'
import validator from '../../../../middlewares/validator'
import Auth from '../../../../middlewares/Auth'
import getUserMenu from '../../../../common/apiValidate/system/user/getUserMenu'
import { getTreeByList, lineToHumpObject, sort } from '../../../../common/utils/utils'
import { User } from '../../../../common/typings/user'
import Config from '../../../../config/Config'
import { Menu } from '../../../../common/typings/menu'
const router = new KoaRouter({
  prefix: `${Config.api_prefix}system/user`,
})

/**
 * 获取当前用户的菜单
 */
router.post('/getUserMenu', Auth.verifyToken, validator(getUserMenu, 'body'), async (ctx: Models.Ctx) => {
  const { roleId } = ctx.request.body
  // 所有的角色
  const roleRes = (
    await Mysql.command(`
      SELECT
        *
      FROM
        role
    `)
  ).results.map(lineToHumpObject)

  // 过滤, 获取当前角色及当前角色的祖先角色的所有记录
  const roleList: User.Role[] = []
  const each = (list: User.Role[], nodeId: number) => {
    const arr = list.filter((item) => item.id === nodeId)
    if (arr.length) {
      roleList.push(...arr)
      each(list, arr[0].parentId)
    }
  }
  each(roleRes, roleId)
  // 当前角色的角色树
  const roleTree = getTreeByList(roleList, 0) as unknown as User.Role[]
  // 当前角色有权限的所有菜单.
  let menuList: number[] = []
  const merge = (list: User.Role[]) => {
    list.forEach((item) => {
      menuList = [...new Set([...menuList, ...item.permissions.split(',').map((str) => Number(str))])]
      if (item.children) {
        merge(item.children)
      }
    })
  }
  // 合并当前角色和当前角色的祖先角色的所有菜单
  merge(roleTree)

  // roleId 字段，角色，与权限相关
  const res = await Mysql.command(`
      SELECT
          menu.id,
          menu.label title,
          menu.show,
          menu.icon,
          menu.component,
          menu.redirect,
          menu.parent_id parentId,
          menu.path,
          menu.hide_children hideChildren,
          menu.serial_num,
          menu.permission,
          menu.type
      FROM
          menu
      WHERE
          FIND_IN_SET(menu.id , '${menuList.join(',')}')
    `)
  const sortEach = (arr: Menu.Menu[]) => {
    sort(arr, 'serialNum', 'desc')
    arr.forEach((item) => {
      if (item.children) {
        sortEach(item.children)
      }
    })
  }
  sortEach(res.results)
  const list = (res.results as Menu.Menu[]).map(
    ({
      name,
      parentId,
      id,
      icon,
      title,
      show,
      component,
      redirect,
      path,
      hideChildren,
      children,
      serialNum,
      permission,
      type,
    }) => {
      return {
        name,
        parentId,
        id,
        meta: {
          icon,
          title,
          show: Boolean(show),
          hideChildren: Boolean(hideChildren),
        },
        component,
        redirect,
        path,
        children,
        serialNum,
        permission,
        type,
      }
    }
  )

  throw new httpErrors.Success(list)
})

export default router
